<template>
  <div class="dashboard-container">
    <el-card class="welcome-card">
      <div class="welcome-header">
        <div class="welcome-info">
          <h2>欢迎，{{ userInfo.username }}</h2>
          <p>{{ userInfo.farmName || '' }}</p>
          <p>{{ getCurrentDate() }}</p>
        </div>
        <div class="welcome-actions">
          <el-button type="success" icon="el-icon-plus" @click="goToInfoEntry">添加产品信息</el-button>
          <el-button type="primary" icon="el-icon-document" @click="goToQRCode">查看溯源码</el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-s-goods stat-icon"></i>
            <div class="stat-info">
              <div class="stat-label">产品总数</div>
              <div class="stat-value">{{ stats.productCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-s-order stat-icon orange"></i>
            <div class="stat-info">
              <div class="stat-label">销售订单</div>
              <div class="stat-value">{{ stats.orderCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-card-header">
            <i class="el-icon-search stat-icon blue"></i>
            <div class="stat-info">
              <div class="stat-label">溯源查询量</div>
              <div class="stat-value">{{ stats.queryCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="clearfix">
              <span>最近批次产品</span>
            </div>
          </template>
          <el-table :data="recentProducts" style="width: 100%" :show-header="false" v-loading="productsLoading">
            <el-table-column prop="createdAt" width="100">
              <template #default="scope">
                <el-tag size="medium">{{ formatDate(scope.row.createdAt) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="name">
              <template #default="scope">
                <div>{{ scope.row.name }}</div>
                <div class="table-desc">批次: {{ scope.row.batchId }}</div>
              </template>
            </el-table-column>
            <el-table-column width="60">
              <template #default="scope">
                <i class="el-icon-arrow-right" @click="viewProduct(scope.row)" style="cursor: pointer;"></i>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="clearfix">
              <span>最近产品</span>
            </div>
          </template>
          <el-table :data="LS" style="width: 100%" v-loading="ordersLoading">
            <el-table-column prop="productName" label="产品名称" width="160"></el-table-column>
            <el-table-column prop="customerName" label="产品编号" width="160"></el-table-column>
            <el-table-column prop="orderDate" label="生产日期" width="160"></el-table-column>
            <el-table-column prop="status" label="产地" width="160">
<!--              <template #default="scope">-->
<!--                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.statusText }}</el-tag>-->
<!--              </template>-->
            </el-table-column>
          </el-table>
<!--          <el-timeline v-loading="activitiesLoading">-->
<!--            <el-timeline-item-->
<!--              v-for="(activity, index) in recentActivities"-->
<!--              :key="index"-->
<!--              :timestamp="formatDateTime(activity.timestamp)"-->
<!--              :color="getActivityColor(activity.type)">-->
<!--              {{ activity.content }}-->
<!--            </el-timeline-item>-->
<!--          </el-timeline>-->
        </el-card>
      </el-col>
    </el-row>

    <el-card class="todo-card">
      <template #header>
        <div class="clearfix">
          <span>待办事项</span>
        </div>
      </template>
      <el-checkbox-group v-model="checkedTodos" @change="handleTodosChange" v-loading="todosLoading">
        <div v-for="(todo, index) in todos" :key="index" class="todo-item">
          <el-checkbox :label="todo.id">{{ todo.content }}</el-checkbox>
          <span class="todo-date">{{ formatDate(todo.dueDate) }}</span>
        </div>
      </el-checkbox-group>
    </el-card>
  </div>
</template>

<script>
// 引入API
import { userAPI, productAPI, farmingAPI, statisticsAPI } from '@/api/api';

export default {
  name: 'FarmerDashboardPageView',
  data() {
    return {
      LS:[
        {productName: '西瓜', customerName: '114512', orderDate: '2025年3月6日', status: '新疆'},
        {productName: '苹果', customerName: '194122', orderDate: '2025年3月7日', status: '山东'},
        {productName: '香蕉', customerName: '110110', orderDate: '2025年3月8日', status: '海南'},
        {productName: '葡萄', customerName: '112334', orderDate: '2025年3月9日', status: '新疆'},
        {productName: '橙子', customerName: '112225', orderDate: '2025年3月10日', status: '江西'},
        {productName: '芒果', customerName: '666878', orderDate: '2025年3月11日', status: '广西'}
      ],
      userInfo: {},
      stats: {
        productCount: 0,
        orderCount: 0,
        queryCount: 0
      },
      recentProducts: [],
      recentActivities: [],
      todos: [],
      checkedTodos: [],
      productsLoading: false,
      activitiesLoading: false,
      todosLoading: false
    }
  },
  created() {
    this.getUserInfo();
  },
  mounted() {
    this.fetchDashboardData();
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await userAPI.getUserInfo();
        console.log('获取到用户信息:', response.data);
        
        if (response.data) {
          this.userInfo = response.data;
          // 获取到用户信息后，再获取其他数据
          this.fetchDashboardData();
        } else {
          console.error('用户信息为空');
          this.$message.error('获取用户信息失败，无法显示仪表盘数据');
        }
      } catch (error) {
        console.error('Failed to fetch user info:', error);
        this.$message.error('获取用户信息失败');
      }
    },
    
    // 获取所有数据
    fetchDashboardData() {
      this.fetchStats();
      this.fetchRecentProducts();
      this.fetchRecentActivities();
      this.fetchTodos();
    },
    
    // 获取统计数据
    async fetchStats() {
      try {
        if (!this.userInfo || !this.userInfo.id) {
          console.warn('用户信息不完整，无法获取统计数据');
          return;
        }
        
        const response = await statisticsAPI.getFarmerStats(this.userInfo.id);
        console.log('获取到统计数据:', response.data);
        
        if (response.data) {
          this.stats = {
            productCount: response.data.productCount || 0,
            orderCount: response.data.orderCount || 0,
            queryCount: response.data.queryCount || 0
          };
        }
      } catch (error) {
        console.error('Failed to fetch stats:', error);
        this.$message.error('获取统计数据失败');
        // 设置默认值
        this.stats = {
          productCount: 0,
          orderCount: 0,
          queryCount: 0
        };
      }
    },
    
    // 获取最近产品
    async fetchRecentProducts() {
      try {
        this.productsLoading = true;
        
        if (!this.userInfo || !this.userInfo.id) {
          console.warn('用户信息不完整，无法获取产品数据');
          this.productsLoading = false;
          return;
        }
        
        const response = await productAPI.getProducts({ 
          pageNum: 1, 
          pageSize: 4,
          farmerId: this.userInfo.id,
          sortBy: 'createdAt',
          sortDir: 'desc'
        });
        
        console.log('获取到产品数据:', response.data);
        
        if (response.data && response.data.list) {
          this.recentProducts = response.data.list;
        } else if (Array.isArray(response.data)) {
          // 如果直接返回数组
          this.recentProducts = response.data;
        } else {
          this.recentProducts = [];
        }
        
        this.productsLoading = false;
      } catch (error) {
        console.error('Failed to fetch recent products:', error);
        this.$message.error('获取最近批次产品失败');
        this.recentProducts = [];
        this.productsLoading = false;
      }
    },
    
    // 获取最近活动
    async fetchRecentActivities() {
      try {
        this.activitiesLoading = true;
        
        if (!this.userInfo || !this.userInfo.id) {
          console.warn('用户信息不完整，无法获取活动数据');
          this.activitiesLoading = false;
          return;
        }
        
        const response = await farmingAPI.getFarmerActivities(this.userInfo.id);
        console.log('获取到活动数据:', response.data);
        
        if (response.data) {
          this.recentActivities = response.data;
        } else {
          this.recentActivities = [];
        }
        
        this.activitiesLoading = false;
      } catch (error) {
        console.error('Failed to fetch recent activities:', error);
        this.$message.error('获取最近活动失败');
        this.recentActivities = [];
        this.activitiesLoading = false;
      }
    },
    
    // 获取待办事项
    async fetchTodos() {
      try {
        this.todosLoading = true;
        
        if (!this.userInfo || !this.userInfo.id) {
          console.warn('用户信息不完整，无法获取待办事项');
          this.todosLoading = false;
          return;
        }
        
        const response = await statisticsAPI.getFarmerTodos(this.userInfo.id);
        console.log('获取到待办事项数据:', response.data);
        
        if (response.data) {
          this.todos = response.data;
          this.checkedTodos = this.todos.filter(todo => todo.completed).map(todo => todo.id);
        } else {
          this.todos = [];
          this.checkedTodos = [];
        }
        
        this.todosLoading = false;
      } catch (error) {
        console.error('Failed to fetch todos:', error);
        this.$message.error('获取待办事项失败');
        this.todos = [];
        this.checkedTodos = [];
        this.todosLoading = false;
      }
    },
    
    // 处理待办事项变化
    async handleTodosChange(value) {
      try {
        // 找出新选中和取消选中的项
        const allTodoIds = this.todos.map(todo => todo.id);
        const completedTodoIds = value;
        const todoItems = [];
        
        allTodoIds.forEach(id => {
          todoItems.push({
            id,
            completed: completedTodoIds.includes(id)
          });
        });
        
        await statisticsAPI.updateFarmerTodos(this.userInfo.id, todoItems);
      } catch (error) {
        console.error('Failed to update todos:', error);
        this.$message.error('更新待办事项失败');
        // 恢复原状态
        this.fetchTodos();
      }
    },
    
    // 查看产品详情
    viewProduct(product) {
      this.$router.push(`/farmer/product-detail/${product.id}`);
    },
    
    // 获取活动颜色
    getActivityColor(type) {
      const colorMap = {
        product: '#67C23A',
        order: '#E6A23C',
        system: '#409EFF',
        trace: '#F56C6C'
      };
      return colorMap[type] || '#909399';
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${this.formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    // 获取当前日期
    getCurrentDate() {
      const date = new Date();
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
    },
    
    // 跳转到信息录入
    goToInfoEntry() {
      this.$router.push('/farmer/info-entry');
    },
    
    // 跳转到溯源码页面
    goToQRCode() {
      this.$router.push('/farmer/qrcode');
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-info h2 {
  margin: 0 0 5px 0;
  font-size: 22px;
}

.welcome-info p {
  margin: 5px 0;
  color: #606266;
}

.welcome-actions {
  display: flex;
  gap: 10px;
}

.stat-card {
  height: 100px;
  margin-bottom: 20px;
}

.stat-card-header {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 32px;
  color: #67C23A;
  margin-right: 15px;
  padding: 10px;
  background-color: rgba(103, 194, 58, 0.1);
  border-radius: 8px;
}

.stat-icon.orange {
  color: #E6A23C;
  background-color: rgba(230, 162, 60, 0.1);
}

.stat-icon.blue {
  color: #409EFF;
  background-color: rgba(64, 158, 255, 0.1);
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 5px;
}

.chart-card {
  margin-bottom: 20px;
  min-height: 350px;
}

.table-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 3px;
}

.todo-card {
  margin-bottom: 20px;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #EBEEF5;
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-date {
  font-size: 12px;
  color: #909399;
}
</style>
